<template>
  <el-scrollbar>
    <div class="page-login-wrap">
      <div class="login-content">
        <div class="login-left">
          <div class="logo-box">
            <!-- <img src="@/assets/svgs/logo.svg" alt="" /> -->
            <span>{{ settings.title }}</span>
          </div>
          <div class="welcome-box">
            <TransitionGroup
              appear
              tag="div"
              enter-active-class="animate__animated animate__bounceInLeft"
            >
              <img src="@/assets/svgs/login-box-bg.svg" key="1" alt="" />
              <div class="text" key="2">欢迎使用本系统</div>
            </TransitionGroup>
          </div>
        </div>
        <div class="login-right">
          <Transition appear enter-active-class="animate__animated animate__bounceInRight">
            <div class="login-form-box">
              <h2 class="page-title">注册</h2>
              <el-form
                ref="ruleFormRef"
                :model="ruleForm"
                :rules="rules"
                class="ruleForm"
                label-position="top"
              >
                <el-form-item label="昵称" prop="nickName">
                  <el-input
                    v-model="ruleForm.nickName"
                    size="large"
                    placeholder="请输入用户昵称"
                    clearable
                  ></el-input>
                </el-form-item>
                <el-form-item label="手机号" prop="phoneNo">
                  <div style="display: flex; width: 100%">
                    <el-input
                      v-model="ruleForm.phoneNo"
                      size="large"
                      placeholder="请输入用户手机号"
                      clearable
                      style="flex: 1"
                    ></el-input>
                    <el-button
                      size="large"
                      :disabled="codeText !== '发送验证码'"
                      @click="sendPhoneCode"
                      style="width: 100px"
                    >
                      {{ codeText }}
                    </el-button>
                  </div>
                </el-form-item>
                <el-form-item label="验证码" prop="phoneCode">
                  <el-input
                    v-model="ruleForm.phoneCode"
                    size="large"
                    type="number"
                    placeholder="请输入手机验证码"
                    clearable
                  ></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                  <el-input
                    v-model="ruleForm.password"
                    type="password"
                    show-password
                    size="large"
                    clearable
                    placeholder="请输入密码"
                  ></el-input>
                </el-form-item>
                <el-form-item label="确认密码" prop="confirmPassword">
                  <el-input
                    v-model="ruleForm.confirmPassword"
                    type="password"
                    show-password
                    size="large"
                    clearable
                    placeholder="请确认密码"
                    @keyup.enter="registerSubmit"
                  ></el-input>
                </el-form-item>
                <el-form-item prop="isRead">
                  <el-checkbox v-model="ruleForm.isRead" @change="onIsReadChange"></el-checkbox>
                  <span
                    >我已阅读并同意<el-link
                      type="primary"
                      :underline="false"
                      href="https://kdocs.cn/l/cpQIkXMN9LKH"
                      target="_blank"
                      >《用户隐私政策》</el-link
                    ></span
                  >
                </el-form-item>
                <el-form-item>
                  <div style="width: 100%">
                    <el-button
                      v-loading="isLoading"
                      type="primary"
                      size="large"
                      style="width: 100%"
                      @click="registerSubmit"
                    >
                      注册
                    </el-button>
                  </div>
                  <div style="margin-top: 20px; width: 100%">
                    <el-button size="large" style="width: 100%" @click="toLogin">
                      已有账号？去登录
                    </el-button>
                  </div>
                </el-form-item>
              </el-form>
            </div>
          </Transition>
        </div>
      </div>
    </div>
  </el-scrollbar>
</template>

<script setup>
import settings from '@/utils/settings'
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import dayjs from 'dayjs'
import { registerApi, verificationCodeApi } from '@/api/login'
import { useLoading } from '@/hooks/loading'
import { ElMessage } from 'element-plus'
const { isLoading, startLoading, endLoading } = useLoading()

const router = useRouter()

const phonenumberReg = /^1[3-9]\d{9}$/
const validPhoneNoPass = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请输入手机号'))
    return
  }
  if (!phonenumberReg.test(value)) {
    callback(new Error('请输入正确手机号格式'))
  }
  callback()
}

const rules = {
  nickName: [
    {
      required: true,
      trigger: 'blur',
      message: '请输入昵称'
    },
    { min: 2, max: 6, message: '长度应在2-6个字符之间', trigger: 'blur' }
  ],
  phoneNo: [
    {
      required: true,
      validator: validPhoneNoPass,
      trigger: 'blur'
    }
  ],
  phoneCode: [
    {
      required: true,
      message: '请输入验证码',
      trigger: 'blur'
    },
    {
      min: 6,
      max: 6,
      message: '请输入6位验证码',
      trigger: 'blur'
    }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        const reg = /(?=.*\d)(?=.*[a-zA-Z])(?=.*[^a-zA-Z0-9]).{6,16}/
        if (reg.test(value)) {
          callback()
        } else {
          callback(new Error())
        }
      },
      message: '密码必须由数字、字母、特殊字符组合,请输入6-16位',
      trigger: 'blur'
    }
  ],
  confirmPassword: [
    { required: true, message: '请输入确认密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== ruleForm.value.password) {
          callback(new Error('与密码不一致'))
        }
        callback()
      },
      trigger: 'blur'
    }
  ],
  isRead: [{ required: true, message: '请先阅读并勾选', trigger: 'change' }]
}

const codeText = ref('发送验证码')
const countDown = ref(60)

let timer
const countDownTimer = () => {
  timer = setInterval(() => {
    countDown.value -= 1
    if (countDown.value === 0) {
      clearInterval(timer)
      codeText.value = '发送验证码'
    } else {
      codeText.value = `${countDown.value}s后重试`
    }
  }, 1000)
}
// 判断上次发送验证码后是否过了60s
if (localStorage.getItem('lastSendCodeTime')) {
  const lastSendCodeTime = localStorage.getItem('lastSendCodeTime')
  const currentTime = new Date().getTime()
  if (currentTime - lastSendCodeTime < 58 * 1000) {
    countDown.value = 58 - Math.floor((currentTime - lastSendCodeTime) / 1000)
    codeText.value = `${countDown.value}s后重试`
    countDownTimer()
  }
}

const sendPhoneCode = async () => {
  if (ruleForm.value.phoneNo && phonenumberReg.test(ruleForm.value.phoneNo)) {
    const res = await verificationCodeApi({
      phoneNo: ruleForm.value.phoneNo
    })
    if (res && res.code === 200) {
      if (timer) return
      localStorage.setItem('lastSendCodeTime', new Date().getTime())
      countDownTimer()
    }
  }
}

const onIsReadChange = (val) => {
  if (val) {
    ruleForm.value.protocolTime = dayjs().format('YYYY-MM-DD HH:mm:ss')
  }
}

const ruleForm = ref({})
const ruleFormRef = ref()

const registerSubmit = () => {
  ruleFormRef.value.validate(async (valid) => {
    if (valid) {
      startLoading()
      const res = await registerApi({ ...ruleForm.value })
      endLoading()
      if (res && res.code === 200) {
        ElMessage.success('注册成功！')
        toLogin()
      }
    }
  })
}

const toLogin = () => {
  router.replace('/login')
}
</script>

<style scoped lang="less">
.page-login-wrap {
  height: 100%;
  position: relative;
  background: var(--login-bg-color);
  .login-content {
    position: relative;
    display: flex;
    min-height: 100vh;
    .login-left {
      padding: 30px;
      width: 50%;
      box-sizing: border-box;
      .logo-box {
        display: flex;
        align-items: center;
        position: relative;
        color: #fff;
        img {
          width: 48px;
          height: 48px;
          margin-right: 10px;
        }
        span {
          font-size: 20px;
          font-weight: bold;
        }
      }
      .welcome-box {
        display: flex;
        justify-content: center;
        align-items: center;
        height: calc(100% - 60px);
        img {
          width: 350px;
        }
        .text {
          color: #fff;
          font-size: 30px;
        }
      }
    }
    .login-right {
      flex: 1;
      min-height: 100%;
      background: #fff;
      display: flex;
      flex-direction: column;
      justify-content: center;
      .login-form-box {
        width: 500px;
        margin: 0 auto;
        padding: 20px;
        box-sizing: border-box;
        h2 {
          font-size: 24px;
          text-align: center;
        }
      }
    }
  }
}
:deep(.el-checkbox) {
  margin-right: 10px !important;
}
</style>
